<?php
/**
 * Процедуры и функции работы с каталогом
 * @category ОбщиеФункции
 */

require_once('config.php');
require_once(DIR_SYSTEM . 'library/db.php');
require_once('cml_exchange_catalog.php');
require_once('cml_exchange.php');

//**************************************************************************************
// Процедуры работы с категориями
function create_array_of_groups_text($str, $parent_uuid, &$data, &$db) {

//    if (feof($f_groups)){
//        return 0;
//    }

    //$str = fgets($f_groups);
    $category_data = explode("|", $str);
    $group_item = array(
        'uuid' => (string) $category_data[0],
        'parent_uuid' => (string) $category_data[2],
        'category_name' => (string) $category_data[1],
        'category_id' => 0,
        'isnew' => false,
        'modified' => false,
        // стандартные данные
        'id' => 0,
        'parent_id' => 0,
        'sort_order' => '0',
        'status' => '1',
        'category_store' => '1',
        'category_description' => array(
            // 1 = Язык по умолчанию!
            1 => array(
                'name' => (string) $category_data[1],
                'meta_description' => '',
                'description' => ''
            )
        ),
        'keyword' => false,
        'category_store' => array(
            0 //Default store
        ),
    );

    $uuid = $group_item['uuid'];
    $result = find_group_by_uuid($uuid, $db);
    if (count($result) == 0) {
        create_new_group($group_item, $db);
    } else {
        update_group($group_item, $db);
    }

    $data[] = $group_item;
//
//    if (strcasecmp($category_data[2], NULL_UUID) != 0) {
//        create_array_of_groups_text($f_groups, $category_data[2], $data, $db);
//    }

}

function create_array_of_products_text($f_goods, &$db) {
    $str = fgets($f_goods); //Пропуск строки №1 - Это заголовок
    while (!feof($f_goods)){
        $str = fgets($f_goods);
        $sku_data = explode("|", $str);

 //   foreach ($xml_product->{"Товары"}->{"Товар"} as $sku_data) {
        $product_groups = "";
        unset($product_groups);
        //foreach ($sku_data->{"Группы"} as $groups) {
        //    $product_groups[] = (string) $groups->{"Ид"};
        //}


        
        $group_uuid = $sku_data[5]; //6-ая колонка
        $group_id = find_group_by_uuid($group_uuid, $db);

        $data_item = array(
            'uuid' => (string) $sku_data[0],
            'group_uuid' => $group_uuid,
            'model' => htmlspecialchars($sku_data[1]),
            'sku' => (string) $sku_data[4], //TODO: Артикул к товару
            'id' => 0,
            'image' => '', //TODO: Прописать пути к картинке
            'status' => '1',
            'location' => '',
            'quantity' => 0.0,
            'minimum' => '0',
            'subtract' => '0',
            'stock_status_id' => '7',
            'date_available' => '01/01/2010',
            'manufacturer_id' => '0',
            'shipping' => '1',
            'price' => 0.0,
            'cost' => '0',
            'weight' => '0.1',
            'weight_class_id' => '1',
            'length' => '0.1',
            'width' => '0.1',
            'height' => '0.1',
            'length_class_id' => '1',
            'status' => '1',
            'tax_class_id' => '0',
            'sort_order' => '0',
            'product_description' => array(
                1 => array(
                    'name' => htmlspecialchars($sku_data[1]),

                    'meta_description' => '',
                    'description' => ''
                )
            ),
            'product_store' => array(
                0
            ),
            'product_category' => array(
                $group_id['category_id']
            ),
            'product_tags' => array(
                0
            ),
            'keyword' => false,
        );

        $product_item = $data_item;
        //update_product_price($data_item, $xml_price);
        $product = find_product_by_uuid($product_item['uuid'], $db);
        if (count($product) == 0) {
            create_product($product_item, $db);
        } else {
            update_product($product_item, $db);
        }
    }
}

function parse_groups_text($dir) {
//    $xml = simplexml_load_file($dir . '/import.xml');
//    $groups_xml = $xml->{"Классификатор"};
//    $db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

    try {
        $data = array();
        $f_groups  = fopen($dir . '/groups.txt', "r");
        $db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
        $str = fgets($f_groups); //Пропуск строки №1 - Это заголовок
        while (!feof($f_groups)){
            $str = fgets($f_groups);
            $category_data = explode("|", $str);
            create_array_of_groups_text($str, $category_data[2], $data, $db);
        }
        fclose($f_groups);
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}


function parse_products_text($dir) {

    try {
        $f_goods  = fopen($dir . '/catalog_of_goods.txt', "r");
        $db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
        create_array_of_products_text($f_goods, $db);
        fclose($f_goods);
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

function parse_price_text($dir){
    //$xml_product_price = simplexml_load_file($dir . '/offers.xml');
    try {
        $f_price  = fopen($dir . '/price.txt', "r");
        $db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
        $str = fgets($f_price); //Пропуск строки №1 - Это заголовок
        $query = $db->query("SELECT * FROM " . DB_PREFIX . "product WHERE `uuid` <> '" . NULL_UUID . "'");
        while (!feof($f_price)){
            $str = fgets($f_price);
            $price_row = explode("|", $str);
            $product_item_quantity = $price_row[4];
            $product_item_price = $price_row[3];
            $product = find_product_by_uuid($price_row[5], $db);            
            $db->query("UPDATE " . DB_PREFIX . "product SET `quantity` = '" . (int)$product_item_quantity . "', `price` = '" . (float)$product_item_price . "' WHERE `product_id` = '" . $product['product_id'] . "'");
        }
        fclose($f_price);
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

//

function parse_text($dir, $filename) {
    try {
        if ($filename === 'catalog_of_goods.txt'){
            parse_products_text($dir);
        } else if ($filename === 'groups.txt') {
            parse_groups_text($dir);
        } else if ($filename === 'price.txt') {
            parse_price_text($dir);
        } else{
            parse_groups_text($dir);
            parse_products_text($dir);
            parse_price_text($dir);
        }
        echo "sucsess";
    }catch (Exception $e) {
        echo 'Caught exception: ',  $e->getMessage(), "\n";
    }
}

?>
